package com.qx.grainmall.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.qx.common.utils.HttpUtils;
import com.qx.common.utils.R;
import com.qx.common.vo.MemberVo;
import com.qx.grainmall.authserver.feig.MemberFeignService;
import com.qx.grainmall.authserver.vo.WeiboAccessTokenVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sun.net.www.http.HttpClient;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
public class LoginController {
    @Autowired
    private MemberFeignService memberFeignService;

    //跳转登陆
    @GetMapping({"login","/"})
    public String login(){
        return "login";
    }
    @GetMapping({"registry"})
    public String registry(){
        return "registry";
    }

    @GetMapping("oauth2.0/weibo/success")
    public String getcode(@RequestParam("code")String code, HttpSession session) throws Exception {
    //拿到code
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","1821999461");
        map.put("client_secret","4c17b3206b18f8a53a3ae5d4d04343ac");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        //执行查询
        HttpResponse httpResponse = HttpUtils.doPost("https://api.weibo.com/oauth2/access_token", "", "post", null, map, "");
        String resp = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        WeiboAccessTokenVo weiboAccessTokenVo = JSON.parseObject(resp, new TypeReference<WeiboAccessTokenVo>() {
        });
        //在我的系统中 为这个微博账户生成 账户
        R r = memberFeignService.weiboLogin(weiboAccessTokenVo);
        if(r.getCode().equals(0)){ //判断是否成功
            MemberVo data = r.getData(new TypeReference<MemberVo>() {
            });
            session.setAttribute("user",data);
            return "redirect:http://gulimall.com";
        }
    return "login";
    }

}
